package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.BusNews;
import com.example.demo.mapper.BusnewsMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: likew
 * @Date: 2022/4/13
 */
@RestController
@RequestMapping("/busfrontnews")
public class BusFrontNewController  extends BaseController{
    @Resource
    BusnewsMapper busnewsMapper;
    
    @PostMapping
    public Result<?> save(@RequestBody BusNews busnews) {
        busnews.setTime(new Date());
        busnewsMapper.insert(busnews);
        return Result.success();
    }
    
    @PutMapping
    public Result<?> update(@RequestBody BusNews busnews) {
        busnewsMapper.updateById(busnews);
        return Result.success();
    }
    
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        busnewsMapper.deleteById(id);
        return Result.success();
    }
    
    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(busnewsMapper.selectById(id));
    }
    
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<BusNews> wrapper = Wrappers.<BusNews>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(BusNews::getTitle, search);
        }
        Page<BusNews> newsPage = busnewsMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(newsPage);
    }
}
